package com.aifast.common.global;

import cn.dev33.satoken.exception.NotLoginException;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.NumberUtil;
import com.aifast.common.base.Controller;
import com.aifast.common.base.R;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import java.math.BigDecimal;

/**
 * @Author fujian
 * @since 2022/1/14 16:18
 */
@ControllerAdvice
public class GlobalException extends Controller {


    private static final String MAIN_URL = "http://localhost:8099/view/login";

    /** 全局异常拦截  */
    @ResponseBody
    @ExceptionHandler
    public R handlerException(Exception e){
        e.printStackTrace();
        if(e instanceof NotLoginException){
            /*本地系统未登录时 向sso中心发送请求 看是否有登录*/
            return R.ERROR(Status.NOLOGIN);
        }
        /*参数校验异常返回*/
        if(e instanceof BindException){
            String result = null;
            BindException e1 = (BindException) e;
            if(e1.getBindingResult().hasErrors()){
                result = e1.getBindingResult().getAllErrors().stream().map(ObjectError::getDefaultMessage).reduce((i1, i2) -> i1 + ";" + i2).orElse("非法参数，请检查接口参数");
            }
            return R.ERROR(result);
        }

        if(e instanceof MaxUploadSizeExceededException){
            char[] chars = e.getMessage().toCharArray();
            StringBuilder tmp = new StringBuilder();
            for (char c: chars){
                boolean number = NumberUtil.isNumber(Convert.toStr(c));
                if(number){
                    tmp.append(c);
                }
            }
            BigDecimal div = NumberUtil.div(Convert.toStr(tmp), Convert.toStr(1024 * 1024) ,0);
            return ERROR("上传文件大小已经超过 " + div + "M 限制") ;
        }

        String message = e.getMessage();
        Console.log(message);

        return R.ERROR(message);
    }

}
